package com.banzhi.shop.activity;


import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banzhi.shop.MyApp;
import com.banzhi.shop.R;
import com.banzhi.shop.adapter.GroupSucaiAdapter;
import com.banzhi.shop.adapter.GuigeAdapter2;
import com.banzhi.shop.adapter.HomeFrgAda;
import com.banzhi.shop.adapter.ViewPagerAdapter;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.data.GroupGuigeBean;
import com.banzhi.shop.data.GroupingDetailsBean;
import com.banzhi.shop.entity.GoodsDetails.Buy_Data;
import com.banzhi.shop.fragment.GoodsIntroductionFragment;
import com.banzhi.shop.fragment.PurchaseNotesFragment;
import com.banzhi.shop.model.CallBack.CommoditySucaiCallBack;
import com.banzhi.shop.model.CallBack.GroupGuigeCallBack;
import com.banzhi.shop.model.CallBack.GroupingDetailsCallback;
import com.banzhi.shop.model.CallBack.SingleBuyCallBack;
import com.banzhi.shop.model.Impl.GroupGuigeImpl;
import com.banzhi.shop.model.Impl.GroupingDetailsImpl;
import com.banzhi.shop.model.Impl.SingleBuyImpl;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.LogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.NumberUtils;
import com.banzhi.shop.utils.TabLayoutUtil;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;
import com.banzhi.shop.utils.XutilImage;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.banzhi.shop.MyApp.context;

//拼团详情
public class GroupingDetailsActivity extends BaseActivity implements GroupingDetailsCallback, View.OnClickListener, GroupGuigeCallBack, GuigeAdapter2.GettextCallBack, SingleBuyCallBack {
    private String mGoodId;
    private ImageView mIvBack;
    private Button mBtXiangqing;
    private Button mBtnSucai;
    private ImageView mIvShare;
    private LinearLayout mLlXiangqing;
    private ViewPager mViewPage;
    private TextView mTvNum;
    private TextView mTvAll;
    private TextView mTvTitle;
    private TextView mGroupNum;
    private TextView mGroupsprice;
    private TextView mGroupProfit;
    private TextView mTvStock;
    private TextView mTvSales;
    private LinearLayout mGamePlay;
    private GroupingDetailsImpl mModel;
    private TabLayout mTabLayout;
    private GroupingDetailsBean mGroupingDetailsBean;
    private List<String> mThumb_url;
    private boolean iscanbuy = true;

    /**
     * 展示图片的imageview集合
     */
    private List<ImageView> mImageViews = new ArrayList<>();
    private ViewPager mViewPager2;
    // private int width;
    private int height;
    private int mWidth;
    private TextView mTvStatu;

    /*    private Timer timer;
        private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                showTimeDate();
            }
        };*/
    private TextView mTvDay;
    private TextView mTvHour;
    private TextView mTvMinute;
    private TextView mTvSecond;
    private RelativeLayout mRlsucai;
    private LinearLayout mLlWantProfit;
    private LinearLayout mLlWantGoods;
    private GroupSucaiAdapter adapter;
    private ListView lvsucai;
    private ImageView mIvBegin;
    private ImageView mIvFinished;
    private TextView mTvOpenprice;
    private TextView mTvOpenprice2;
    private LinearLayout mLlBackgroud;
    private RelativeLayout mRlChoiceGuige;
    private TextView mTvChoice;
    private GroupGuigeImpl mGroupGuigeModel;

    /**
     * 点击选择规格你的确定时  来判断去做什么事情
     * 点击选择规格  type ==1；
     * 点击加入购物车  type ==2;
     * 点击买        type==3;
     */
    private int type = 1;
    private GroupGuigeBean mGuigeData;
    private GuigeAdapter2 mGuigeAdapter2;
    private int[] strs;
    private String mStock;
    private RecyclerView mRecyclerView;


    private LinearLayoutManager mLinearLayoutManager;
    private TextView mTv;
    private View mView;
    /*   private List<GroupingDetailsBean.OtherBean> mOther;
       private List<GroupingDetailsBean.OtherBean> mOtherBeans;*/
    private List<GroupingDetailsBean.OtherBean> mBeans;
    private List<GroupingDetailsBean.OtherBean> mOtherBeans = new ArrayList<>();
    private BaseQuickAdapter<GroupingDetailsBean.OtherBean, BaseViewHolder> mQuickAdapter;

    private int position;
    private String teamid;
    private LinearLayout mLlBuy;
    private SingleBuyImpl mBuyModel;
    private TextView mMarketPrice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grouping_details);
        Translucent.setTranslucent(this);
        initViews();
        setListener();

        Intent intent = getIntent();
        mGoodId = intent.getStringExtra("id");

        showFragment();
        mModel = new GroupingDetailsImpl();
        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
        mModel.getGroupingDetailsData(mGoodId, this);
        //拼团规格
        mGroupGuigeModel = new GroupGuigeImpl();
        mBuyModel = new SingleBuyImpl();
        SharedPreferences.Editor editor = MyApp.loginMessage.edit();
        editor.putString("teamid", "");
        editor.putString("tt", "");
        editor.apply();
    }

    public String getGoodID() {
        return mGoodId;
    }


    @Override
    protected void onStart() {
        super.onStart();
        mTabLayout.post(new Runnable() {
            @Override
            public void run() {
                TabLayoutUtil.setIndicator(mTabLayout, 50, 50);
            }
        });
    }

    private void showFragment() {
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(new GoodsIntroductionFragment());//商品介绍
        fragments.add(new PurchaseNotesFragment());//详情参数
        List<String> list_title = new ArrayList<>();
        list_title.add("商品介绍");
        list_title.add("活动须知");
        HomeFrgAda frgAda = new HomeFrgAda(getSupportFragmentManager(), fragments, list_title);
        mViewPager2.setAdapter(frgAda);
        mTabLayout.setupWithViewPager(mViewPager2);
    }

    private void initViews() {
        mMarketPrice = (TextView) findViewById(R.id.tv_market_price);
        mLlBuy = (LinearLayout) findViewById(R.id.ll_buy);
        mIvBack = (ImageView) findViewById(R.id.iv_back);
        mBtXiangqing = (Button) findViewById(R.id.btn_xiangqing);
        mBtnSucai = (Button) findViewById(R.id.btn_sucai);
        mIvShare = (ImageView) findViewById(R.id.iv_share);
        mLlXiangqing = (LinearLayout) findViewById(R.id.ll_xiangqing);
        mRlsucai = (RelativeLayout) findViewById(R.id.rl_sucai);
        mViewPage = (ViewPager) findViewById(R.id.vp_grouping);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        mWidth = dm.widthPixels;
        height = mWidth;
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, height);
        mViewPage.setLayoutParams(params);
        mTvNum = (TextView) findViewById(R.id.tv_num);
        mTvAll = (TextView) findViewById(R.id.tv_all);
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mGroupNum = (TextView) findViewById(R.id.groupnum);
        mGroupsprice = (TextView) findViewById(R.id.groupsprice);
        mGroupProfit = (TextView) findViewById(R.id.group_profit);
        mTvStock = (TextView) findViewById(R.id.tv_stock);
        mTvSales = (TextView) findViewById(R.id.tv_sales);
        mGamePlay = (LinearLayout) findViewById(R.id.ll_gameplay);
        mTabLayout = (TabLayout) findViewById(R.id.tab_grouping);
        mViewPager2 = (ViewPager) findViewById(R.id.vp_grouping_data);
        mTvStatu = (TextView) findViewById(R.id.tv_statu_grouping);
        mTvDay = (TextView) findViewById(R.id.tv_day);
        mTvHour = (TextView) findViewById(R.id.tv_hour);
        mTvMinute = (TextView) findViewById(R.id.tv_minute);
        mTvSecond = (TextView) findViewById(R.id.tv_second);
        mLlWantProfit = (LinearLayout) findViewById(R.id.ll_want_profit);
        mLlWantGoods = (LinearLayout) findViewById(R.id.ll_want_goods);
        lvsucai = (ListView) findViewById(R.id.sucai_listview);
        mIvBegin = (ImageView) findViewById(R.id.iv_begin);
        mIvFinished = (ImageView) findViewById(R.id.iv_finished);
        mTvOpenprice = (TextView) findViewById(R.id.tv_openprice1);
        mTvOpenprice2 = (TextView) findViewById(R.id.tv_openprice2);
        mLlBackgroud = (LinearLayout) findViewById(R.id.ll_backgroud);
        mRlChoiceGuige = (RelativeLayout) findViewById(R.id.rl_choice_guige);
        mTvChoice = (TextView) findViewById(R.id.tv_choice);
        mTv = (TextView) findViewById(R.id.tv_des);
        mView = findViewById(R.id.view);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        mLinearLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);


        mQuickAdapter = new BaseQuickAdapter<GroupingDetailsBean.OtherBean, com.chad.library.adapter.base.BaseViewHolder>(R.layout.recyclerview_item_group2) {
            @Override
            protected void convert(com.chad.library.adapter.base.BaseViewHolder helper, final GroupingDetailsBean.OtherBean item) {
                helper.setText(R.id.nickname,item.getNickname());
                helper.setText(R.id.dispart,item.getDispart());
                if (ASUtils.isCanUse(item.getAvatar())) {
                    Picasso.with(context).load(item.getAvatar()).placeholder(R.mipmap.zhanweitu2).into((ImageView) helper.getView(R.id.civ));
                }



                //    LogUtils.e("步骤:",3+"");
           /*     SharedPreferences.Editor editor = MyApp.loginMessage.edit();
                editor.putString("teamid", item.getTeamid());
                editor.putString("tt", "1");
                editor.apply();*/



                helper.getView(R.id.join).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        teamid = item.getTeamid();
                     //   LogUtils.e("teamid", teamid);
                        if ("0".equals(mGroupingDetailsBean.getHasoption())) {
                            ToastUtils.makeToastShort("商品没有规格了");
                        } else {
                            type = 4;
                            LogUtils.e("步骤:","1");

                            if (mGuigeData == null) {
                                LoadingDialogUtils.showProgress(GroupingDetailsActivity.this, "正在加载,请稍后~");
                                mGroupGuigeModel.getGroupGuigeData(mGroupingDetailsBean.getId(), GroupingDetailsActivity.this);
                            } else {
                                showGuige();
                            }
                        }

                    }
                });

            }
        };
        mQuickAdapter.bindToRecyclerView(mRecyclerView);


    }

    private void setListener() {
        mLlBuy.setOnClickListener(this);
        mRlChoiceGuige.setOnClickListener(this);
        mGamePlay.setOnClickListener(this);
        mIvBack.setOnClickListener(this);
        mBtXiangqing.setOnClickListener(this);
        mBtnSucai.setOnClickListener(this);
        //  mLlWantProfit.setOnClickListener(this);
        //  mLlWantGoods.setOnClickListener(this);

        mViewPage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mTvNum.setText(position + 1 + "");

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_gameplay:
                Intent intent2 = new Intent(this, GroupPlayActivity.class);
                startActivity(intent2);
                break;
            case R.id.btn_xiangqing:
                mBtXiangqing.setBackgroundResource(R.mipmap.bg1);
                mBtnSucai.setBackgroundResource(R.mipmap.bg2);
                mLlXiangqing.setVisibility(View.VISIBLE);
                mRlsucai.setVisibility(View.GONE);
                mBtXiangqing.setTextColor(ContextCompat.getColor(this, R.color.themeColor));
                mBtnSucai.setTextColor(Color.WHITE);
                break;
            case R.id.btn_sucai:
                mBtXiangqing.setBackgroundResource(R.mipmap.bg4);
                mBtnSucai.setBackgroundResource(R.mipmap.bg5);
                mLlXiangqing.setVisibility(View.GONE);
                mRlsucai.setVisibility(View.VISIBLE);
                mBtnSucai.setTextColor(ContextCompat.getColor(this, R.color.themeColor));
                mBtXiangqing.setTextColor(Color.WHITE);
                break;
            case R.id.rl_choice_guige:
                //规格选择
                if ("0".equals(mGroupingDetailsBean.getHasoption())) {
                    ToastUtils.makeToastShort("商品没有规格了");
                } else {
                    type = 1;
                    if (mGuigeData == null) {
                        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                        mGroupGuigeModel.getGroupGuigeData(mGroupingDetailsBean.getId(), this);
                    } else {
                        showGuige();
                    }
                }
                break;

        }


    }

    @Override
    public void ongetGroupingDetailsDataSuccess(Object object) {
        mGroupingDetailsBean = (GroupingDetailsBean) object;
        mBeans = mGroupingDetailsBean.getOther();
        if (mBeans!= null && mBeans.size()>0) {

            if (mBeans.size()>2) {
                for (int i = 0; i < 2; i++) {
                    mOtherBeans.add(mBeans.get(i));
                }
                mQuickAdapter.setNewData( mOtherBeans);
                mTv.setVisibility(View.VISIBLE);
                mView.setVisibility(View.VISIBLE);
            }else  {
            mQuickAdapter.setNewData(mBeans);
             mTv.setVisibility(View.VISIBLE);
             mView.setVisibility(View.VISIBLE);
        }
      }/*else {
            mTv.setVisibility(View.GONE);
            mView.setVisibility(View.GONE);
        }*/
        showGoodsData();

        showSuCaiData();
    }

    private void showSuCaiData() {
        List<GroupingDetailsBean> mGroupingDetailsBeans = new ArrayList<>();
        mGroupingDetailsBeans.add(mGroupingDetailsBean);
        if (adapter == null) {
            adapter = new GroupSucaiAdapter(this, mGroupingDetailsBeans);
            lvsucai.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        LoadingDialogUtils.dismiss();
    }



    private void showGoodsData() {
        if ("0".equals(mGroupingDetailsBean.getStock())) {
            mIvFinished.setVisibility(View.VISIBLE);
            mLlBackgroud.setBackgroundColor(getResources().getColor(R.color.gray));
            mLlBackgroud.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                }
            });
        } else {
            mLlBuy.setBackgroundColor(getResources().getColor(R.color.themeColor));
           // mLlBuy.setBackgroundColor(getResources().getColor(R.color.red2));
            mLlBuy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if ("".equals(MyApp.loginMessage.getString("token", ""))) {
                        showLoginPopupWindow();
                    }else {

                        if (iscanbuy) {
                            type = 5;
                            if (mGuigeData == null) {
                                LoadingDialogUtils.showProgress(GroupingDetailsActivity.this, "正在加载,请稍后~");
                                mGroupGuigeModel.getGroupGuigeData(mGroupingDetailsBean.getId(), GroupingDetailsActivity.this);
                            } else {
                                showGuige();
                            }

                        } else {
                            ToastUtils.makeToastShort("特卖还没开始，请等待");
                        }
                    }
                }
            });
            mLlWantProfit.setBackgroundColor(getResources().getColor(R.color.themeColor));
            mLlWantGoods.setBackgroundColor(getResources().getColor(R.color.red2));
            mLlWantProfit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!"".equals(MyApp.loginMessage.getString("token",""))) {
                        if (!"1".equals(MyApp.loginMessage.getString("isagent",""))) {
                           // ToastUtils.makeToastShort("非店长不能开团");

                            return;
                        }
                        if ("0".equals(mGroupingDetailsBean.getHasoption())) {
                            Intent intent = new Intent(GroupingDetailsActivity.this, ConfirmOrderProfitActivity.class);
                            intent.putExtra("mGoodId", mGoodId);
                            intent.putExtra("type", 1 + "");
                            startActivity(intent);
                        } else {
                            //拿利润
                            //规格选择
                            type = 2;
                            if (mGuigeData == null) {
                                LoadingDialogUtils.showProgress(GroupingDetailsActivity.this, "正在加载,请稍后~");
                                mGroupGuigeModel.getGroupGuigeData(mGroupingDetailsBean.getId(), GroupingDetailsActivity.this);

                            } else {
                                showGuige();

                            }
                        }
                    }
                    else {
                        showLoginPopupWindow();
                    }
                }
            });

            mLlWantGoods.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if (!"".equals(MyApp.loginMessage.getString("token", ""))) {
                        //拿商品
                        //规格选择
                        //判断是否是店长
                        if (!"1".equals(MyApp.loginMessage.getString("isagent",""))) {
                         //   ToastUtils.makeToastShort("非店长不能开团");
                            showBeShoperPopupWindow();
                            return;
                        }
                        if ("0".equals(mGroupingDetailsBean.getHasoption())) {
                            Intent intent1 = new Intent(GroupingDetailsActivity.this, ConfirmOrderGoodsActivity.class);
                            intent1.putExtra("mGoodId", mGoodId);
                            intent1.putExtra("type", 2 + "");
                            startActivity(intent1);
                        } else {
                            type = 3;
                            if (mGuigeData == null) {
                                LoadingDialogUtils.showProgress(GroupingDetailsActivity.this, "正在加载,请稍后~");
                                mGroupGuigeModel.getGroupGuigeData(mGroupingDetailsBean.getId(), GroupingDetailsActivity.this);
                            } else {
                                showGuige();

                            }
                        }

                    }else {
                        showLoginPopupWindow();
                    }

                }

            });
        }
        //展示图片
        mThumb_url = mGroupingDetailsBean.getThumb_url();
        mTvAll.setText(mThumb_url.size() + "");
        prepareData();
        ViewPagerAdapter adapter = new ViewPagerAdapter(mImageViews);
        mViewPage.setAdapter(adapter);
        mTvTitle.setText(mGroupingDetailsBean.getTitle());
        mGroupsprice.setText(mGroupingDetailsBean.getGroupsprice());
        mGroupProfit.setText(mGroupingDetailsBean.getProfit());
        mGroupNum.setText(mGroupingDetailsBean.getGroupnum());
        mTvStock.setText(mGroupingDetailsBean.getStock());
        mTvSales.setText(mGroupingDetailsBean.getSales());

        mTvOpenprice.setText(mGroupingDetailsBean.getOpenprice());
        mTvOpenprice2.setText(mGroupingDetailsBean.getOpenprice());
        mMarketPrice.setText(mGroupingDetailsBean.getGroupsprice());
    }

    private void showBeShoperPopupWindow() {
        View contentView = LayoutInflater.from(GroupingDetailsActivity.this).inflate(R.layout.popupwindow_shoper, null);
        int width = LinearLayout.LayoutParams.MATCH_PARENT;
        int height = WindowManager.LayoutParams.MATCH_PARENT;
        final PopupWindow popupWindow = new PopupWindow(contentView, width, height);
        popupWindow.setAnimationStyle(R.style.AnimBottom);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);//允许在外点击消失
        //设置各个控件 的点击相应
        TextView tvCancle = (TextView) contentView.findViewById(R.id.tv_cancle);
        TextView tvTrue = (TextView) contentView.findViewById(R.id.tv_true);
        tvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        tvTrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //   LoadingDialogUtils.showProgress(CommodityDetailsActivity.this, "正在上架,请稍后~");

                startActivity(new Intent(GroupingDetailsActivity.this,BecomeShoperActivity.class));

                popupWindow.dismiss();
            }
        });

        View rootView = LayoutInflater.from(GroupingDetailsActivity.this).inflate(R.layout.activity_grouping_details, null);
        popupWindow.showAtLocation(rootView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);

    }

    private void showLoginPopupWindow() {
        View contentView = LayoutInflater.from(GroupingDetailsActivity.this).inflate(R.layout.popupwindow_login, null);
        int width = LinearLayout.LayoutParams.MATCH_PARENT;
        int height = WindowManager.LayoutParams.MATCH_PARENT;
        final PopupWindow popupWindow = new PopupWindow(contentView, width, height);
        popupWindow.setAnimationStyle(R.style.AnimBottom);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);//允许在外点击消失
        //设置各个控件 的点击相应
        TextView tvCancle = (TextView) contentView.findViewById(R.id.tv_cancle);
        TextView tvTrue = (TextView) contentView.findViewById(R.id.tv_true);
        tvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        tvTrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //   LoadingDialogUtils.showProgress(CommodityDetailsActivity.this, "正在上架,请稍后~");

                startActivity(new Intent(GroupingDetailsActivity.this,NewLoginActivity.class));
                SharedPreferences.Editor editor = MyApp.loginMessage.edit();
                editor.putString("token", "");
                editor.putString("personNickname", "");
                editor.putString("personAvatar", "");
                editor.putString("personBirth", "");
                editor.putString("personGender", "");
                editor.putString("shopname", "");
                editor.putString("shoplogo", "");
                editor.putString("shopimg", "");
                editor.putString("shopDescription", "");
                editor.putString("recommendName", "");
                editor.putString("isagent","");
                editor.apply();
                finishAllActivity();
                popupWindow.dismiss();
            }
        });

        View rootView = LayoutInflater.from(GroupingDetailsActivity.this).inflate(R.layout.activity_grouping_details, null);
        popupWindow.showAtLocation(rootView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private void prepareData() {
        ImageView iv;

        for (int i = 0; i < mThumb_url.size(); i++) {
            iv = new ImageView(this);
            XutilImage.display(iv, mThumb_url.get(i));
            mImageViews.add(iv);
        }
    }

    @Override
    public void ongetGroupingDetailsDataError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
        LoadingDialogUtils.dismiss();

    }

    @Override
    public void getGroupGuigeSuccess(Object object) {
        mGuigeData = (GroupGuigeBean) object;

        showGuige();

    }

    private void showGuige() {
        ////点击了选择规格
        if (type == 1) {
            showguigePopupwindow();

        } else if (type == 2) {
            mStock = mGroupingDetailsBean.getStock();
            if (ASUtils.isCanUse(mStock) && Integer.parseInt(mStock) > 0) {
                if (mGuigeData.getSpecs() != null) {
                    if (guige != null && goodsnum != null) {
                        for (int i = 0; i < mGuigeData.getOptions().size(); i++) {
                            if (guige.equals(mGuigeData.getOptions().get(i).getSpecs())) {
                                guigeid = mGuigeData.getOptions().get(i).getId();

                            }
                        }
                        //跳转拿商品界面
                        Intent intent1 = new Intent(GroupingDetailsActivity.this, ConfirmOrderProfitActivity.class);
                        intent1.putExtra("mGoodId", mGoodId);
                        intent1.putExtra("type", 1 + "");
                        intent1.putExtra("optionid", guigeid);
                        intent1.putExtra("guigetitle", guigetitle);

                        startActivity(intent1);

                    } else {
                        showguigePopupwindow();
                    }
                } else {
                    if (goodsnum == null) {
                        showguigePopupwindow();
                    } else {
                        //跳转拿商品界面
                        Intent intent1 = new Intent(GroupingDetailsActivity.this, ConfirmOrderProfitActivity.class);
                        intent1.putExtra("mGoodId", mGoodId);
                        intent1.putExtra("type", 1 + "");
                        intent1.putExtra("optionid", guigeid);
                        intent1.putExtra("guigetitle", guigetitle);
                        startActivity(intent1);
                    }
                }
            } else {
                ToastUtils.makeToastShort("商品库存为0");
            }


        } else if (type == 3) {
            mStock = mGroupingDetailsBean.getStock();
            if (ASUtils.isCanUse(mStock) && Integer.parseInt(mStock) > 0) {
                if (mGuigeData.getSpecs() != null) {
                    if (guige != null && goodsnum != null) {
                        for (int i = 0; i < mGuigeData.getOptions().size(); i++) {
                            if (guige.equals(mGuigeData.getOptions().get(i).getSpecs())) {
                                guigeid = mGuigeData.getOptions().get(i).getId();

                            }
                        }
                        //跳转拿商品界面
                        Intent intent1 = new Intent(GroupingDetailsActivity.this, ConfirmOrderGoodsActivity.class);
                        intent1.putExtra("mGoodId", mGoodId);
                        intent1.putExtra("type", 2 + "");
                        intent1.putExtra("optionid", guigeid);
                     //   intent1.putExtra("teamid",mBeans.get(position).getTeamid());
                        intent1.putExtra("guigetitle", guigetitle);
                        intent1.putExtra("price",guigejiage);
                        startActivity(intent1);

                    } else {
                        showguigePopupwindow();
                    }
                } else {
                    if (goodsnum == null) {
                        showguigePopupwindow();
                    } else {
                        //跳转拿商品界面
                        Intent intent1 = new Intent(GroupingDetailsActivity.this, ConfirmOrderGoodsActivity.class);
                        intent1.putExtra("mGoodId", mGoodId);
                        intent1.putExtra("type", 2 + "");
                        intent1.putExtra("optionid", guigeid);
                        intent1.putExtra("guigetitle", guigetitle);
                        intent1.putExtra("price",guigejiage);
                     //   intent1.putExtra("teamid",mBeans.get(position).getTeamid());
                        startActivity(intent1);
                    }
                }
            } else {
                ToastUtils.makeToastShort("商品库存为0");
            }
        } else if (type == 4) {
            mStock = mGroupingDetailsBean.getStock();
            if (ASUtils.isCanUse(mStock) && Integer.parseInt(mStock) > 0) {
                if (mGuigeData.getSpecs() != null) {
                    if (guige != null && goodsnum != null) {
                        for (int i = 0; i < mGuigeData.getOptions().size(); i++) {
                            if (guige.equals(mGuigeData.getOptions().get(i).getSpecs())) {
                                guigeid = mGuigeData.getOptions().get(i).getId();

                            }
                        }
                        //跳转拿商品界面
                        Intent intent1 = new Intent(GroupingDetailsActivity.this, ConfirmOrderGoodsActivity.class);
                        intent1.putExtra("mGoodId", mGoodId);
                        intent1.putExtra("type", 2 + "");
                        intent1.putExtra("optionid", guigeid);
                        intent1.putExtra("guigetitle", guigetitle);
                        intent1.putExtra("price",guigejiage);
                        intent1.putExtra("tt","1");
                        intent1.putExtra("teamid",teamid);
                        intent1.putExtra("flag","3");//参团
                        startActivity(intent1);

                    } else {
                        showguigePopupwindow();
                    }
                } else {
                    if (goodsnum == null) {
                        showguigePopupwindow();
                    } else {
                        //跳转拿商品界面
                        Intent intent1 = new Intent(GroupingDetailsActivity.this, ConfirmOrderGoodsActivity.class);
                        intent1.putExtra("mGoodId", mGoodId);
                        intent1.putExtra("type", 2 + "");
                        intent1.putExtra("optionid", guigeid);
                        intent1.putExtra("guigetitle", guigetitle);
                        intent1.putExtra("price",guigejiage);
                        intent1.putExtra("tt","1");
                        intent1.putExtra("teamid",teamid);
                        intent1.putExtra("flag","3");//参团
                        startActivity(intent1);
                    }
                }
            } else {
                ToastUtils.makeToastShort("商品库存为0");
            }
        }else if (type == 5) {
            //库存量
            mStock = mGroupingDetailsBean.getStock();
            if (mGuigeData.getSpecs() != null) {
                if (guige != null && goodsnum != null) {
                    for (int i = 0; i < mGuigeData.getOptions().size(); i++) {
                        if (guige.equals(mGuigeData.getOptions().get(i).getSpecs())) {
                            guigeid = mGuigeData.getOptions().get(i).getId();

                        }
                    }
                        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                     //   sucaiModel.buy(goodID, goodsnum, guigeid, this);
                        mBuyModel.buy(mGoodId, goodsnum, guigeid, this);
                    } else {
                        showguigePopupwindow();
                    }
                } else {
                    if (goodsnum == null) {
                        showguigePopupwindow();
                    } else {
                        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                        mBuyModel.buy(mGoodId, goodsnum, guigeid, this);
                    }
                }
            } else {
                ToastUtils.makeToastShort("商品库存为0");
            }
        }


    /**
     * 选择规格里的价格
     */
    private TextView tvguigeprice;
    /**
     * 选择规格里的库存
     */
    private TextView tvguigekucun;
    // private TextView tvguigeliyun;
    private ImageView ivguigeimage;
    private LinearLayout ll_guigekucun;
    private int number = 1;
    /**
     * 用来存储商品选择后的规格
     */
    private String guige;
    /**
     * 用来选择商品选择后数量
     */
    private String goodsnum;


    private void showguigePopupwindow() {
        //   LogUtils.e("步骤:",5+"");
        //设置contentView
        View contentView = LayoutInflater.from(GroupingDetailsActivity.this).inflate(R.layout.popupwindow_choice_guige2, null);
        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失
        //设置各个控件的点击响应
        ImageView ivchacha = (ImageView) contentView.findViewById(R.id.iv_chacha);
        ImageView ivimage = (ImageView) contentView.findViewById(R.id.iv_image);
        tvguigeprice = (TextView) contentView.findViewById(R.id.tv_price);
        //  tvguigeliyun = (TextView) contentView.findViewById(R.id.tv_liyun);
        tvguigekucun = (TextView) contentView.findViewById(R.id.tv_guige_kucun);
        ivguigeimage = (ImageView) contentView.findViewById(R.id.iv_image);
        ll_guigekucun = (LinearLayout) contentView.findViewById(R.id.ll_guigekucun);
        final TextView tvjian = (TextView) contentView.findViewById(R.id.tv_jian);
        final TextView tvjia = (TextView) contentView.findViewById(R.id.tv_jia);
        final TextView tvnum = (TextView) contentView.findViewById(R.id.tv_num);
        Button btntrue = (Button) contentView.findViewById(R.id.btn_true);
        ListView listviewgg = (ListView) contentView.findViewById(R.id.listview_guige);

        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        rlbackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        if (mGuigeData != null) {
            mGuigeAdapter2 = new GuigeAdapter2(this, mGuigeData.getSpecs());
            listviewgg.setAdapter(mGuigeAdapter2);

            if (mGuigeData.getSpecs().size() > 0) {
                strs = new int[mGuigeData.getSpecs().size()];
            }
            mGuigeAdapter2.setCallBack(this);
            if (ASUtils.isCanUse(mGroupingDetailsBean.getGroupsprice())) {
                tvguigeprice.setText(mGroupingDetailsBean.getGroupsprice());
            }

            if (ASUtils.isCanUse(mGroupingDetailsBean.getThumb_url().get(0))) {
                Picasso.with(this).load(mGroupingDetailsBean.getThumb_url().get(0)).placeholder(R.mipmap.zhanweitu2).into(ivguigeimage);
            }
            tvguigekucun.setText(mGroupingDetailsBean.getStock());

            if (mGroupingDetailsBean.getThumb_url().size() > 0) {
                Picasso.with(this).load(mGroupingDetailsBean.getThumb_url().get(0)).placeholder(R.mipmap.zhanweitu2).into(ivimage);
            }
        }
        tvnum.setText(number + "");
        if (number == 1) {
            tvjian.setEnabled(false);
        }
        tvjian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             /*   if (number > 1) {
                    number--;
                } else {
                    number = 1;
                }
                if (number == 1) {
                    tvjian.setEnabled(false);
                }
                tvnum.setText(number + "");*/
            }
        });

        tvjia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
       /*         if ("1".equals(goodsdata.getShowtotal()) && Integer.parseInt(tvguigekucun.getText().toString().trim()) <= number) {
                    ToastUtils.makeToastShort("该规格商品库存不足");
                } else {
                    if (goodsdata.getUsermaxbuy() != 0 && number >= goodsdata.getUsermaxbuy() - goodsdata.getUserbuy()) {
                        ToastUtils.makeToastShort("已超过最大限购数量");
                    } else {
                        number++;
                        tvnum.setText(number + "");
                        tvjian.setEnabled(true);
                    }
                }*/
            }
        });
        ivchacha.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                number = 1;
                popWindow.dismiss();
            }
        });
        btntrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if ("1".equals(mGroupingDetailsBean.getShowstock()) && "0".equals(tvguigekucun.getText().toString().trim())) {
                    ToastUtils.makeToastShort("商品库存为0，请选择别的规格");
                } else {
                  /*  if (goodsdata.getUsermaxbuy() != 0 && number > goodsdata.getUsermaxbuy() - goodsdata.getUserbuy()) {
                        ToastUtils.makeToastShort("此账号已购买过" + goodsdata.getUsermaxbuy() + "件");
                    } else {*/
                    if (strs != null) {
                        for (int i = 0; i < strs.length; i++) {
                            if (strs[i] == 0) {
                                isallcheck = false;
                                break;
                            } else {
                                isallcheck = true;
                                continue;
                            }
                        }
                    } else {
                        isallcheck = true;
                    }

                    if (!isallcheck) {
                        ToastUtils.makeToastShort("请选择规格");
                    } else {
                        //判断是由哪个按钮调起的选择规格 ，做不同的事情
                          /*  goodsnum = tvnum.getText().toString().trim();*/
                        goodsnum = 1 + "";
                        if (type == 1) {
                            if (guige != null) {
                                mTvChoice.setText("已选:" + "数量×" + goodsnum + "  " + guigetitle);
                            } else {
                                mTvChoice.setText("已选:" + "数量×" + goodsnum);
                            }
                        /*        if (ASUtils.isCanUse(guigelirun)) {
                                    tvlirun.setText(NumberUtils.DecimalFormat(guigelirun));
                                }*/
                            if (ASUtils.isCanUse(guigekuchun)) {
                                mTvStock.setText(guigekuchun);
                            }
                            if (ASUtils.isCanUse(guigejiage)) {
                                mGroupsprice.setText(NumberUtils.DecimalFormat(guigejiage));
                            }
                        } else if (type == 2) {
                       /*     if (ASUtils.isCanUse(guigelirun)) {
                                    tvlirun.setText(NumberUtils.DecimalFormat(guigelirun));
                                }
                                if (ASUtils.isCanUse(guigekuchun)) {
                                    tvkucun.setText(guigekuchun);
                                }
                                if (ASUtils.isCanUse(guigejiage)) {
                                    tvprice.setText(NumberUtils.DecimalFormat(guigejiage));
                                }
                              *//*  LoadingDialogUtils.showProgress(CommodityDetailsActivity.this, "正在加载,请稍后~");
                                sucaiModel.addCart(goodID, goodsnum, guigeid, CommodityDetailsActivity.this);*//*
                                if (guige != null) {
                                    tvchoice.setText("已选:" + "数量×" + goodsnum + "  " + guige);
                                } else {
                                    tvchoice.setText("已选:" + "数量×" + goodsnum);
                                }*/
                            if (guige != null) {
                                mTvChoice.setText("已选:" + "数量×" + goodsnum + "  " + guigetitle);
                            } else {
                                mTvChoice.setText("已选:" + "数量×" + goodsnum);
                            }
                            Intent intent1 = new Intent(GroupingDetailsActivity.this, ConfirmOrderProfitActivity.class);
                            intent1.putExtra("mGoodId", mGoodId);
                            intent1.putExtra("type", 1 + "");
                            intent1.putExtra("optionid", guigeid);
                            intent1.putExtra("guigetitle", guigetitle);
                            startActivity(intent1);
                        } else if (type == 3) {
                            if (guige != null) {
                                mTvChoice.setText("已选:" + "数量×" + goodsnum + "  " + guigetitle);
                            } else {
                                mTvChoice.setText("已选:" + "数量×" + goodsnum);
                            }
                            Intent intent1 = new Intent(GroupingDetailsActivity.this, ConfirmOrderGoodsActivity.class);
                            intent1.putExtra("mGoodId", mGoodId);
                            intent1.putExtra("type", 2 + "");
                            intent1.putExtra("optionid", guigeid);
                            intent1.putExtra("guigetitle", guigetitle);
                            intent1.putExtra("price",guigejiage);
                            startActivity(intent1);
                        } else if (type == 4) {
                            if (guige != null) {
                                mTvChoice.setText("已选:" + "数量×" + goodsnum + "  " + guigetitle);
                            } else {
                                mTvChoice.setText("已选:" + "数量×" + goodsnum);
                            }

                            Intent intent1 = new Intent(GroupingDetailsActivity.this, ConfirmOrderGoodsActivity.class);
                            intent1.putExtra("mGoodId", mGoodId);
                            intent1.putExtra("type", 2 + "");
                            intent1.putExtra("optionid", guigeid);
                            intent1.putExtra("price",guigejiage);
                            intent1.putExtra("guigetitle", guigetitle);
                            intent1.putExtra("tt","1");
                            intent1.putExtra("flag","3");//参团
                            intent1.putExtra("teamid",teamid);
                            startActivity(intent1);
                        } else if (type == 5) {
                            if (guige != null) {
                                mTvChoice.setText("已选:" + "数量×" + goodsnum + "  " + guigetitle);
                            } else {
                                mTvChoice.setText("已选:" + "数量×" + goodsnum);
                            }
                            LoadingDialogUtils.showProgress(GroupingDetailsActivity.this, "正在加载,请稍后~");
                            mBuyModel.buy(mGoodId, goodsnum, guigeid, GroupingDetailsActivity.this);
                        }
                        //值还原
                        number = 1;
                        type = 1;
                        popWindow.dismiss();
                    }
                }
            }
        });
        ColorDrawable dw = new ColorDrawable(0x70000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(contentView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

    }

    /**
     * 判断是不是全部选择了规格
     */
    private boolean isallcheck;
    private StringBuffer allguige = new StringBuffer();
    private String guigejiage;
    private String guigekuchun;
    private String guigelirun;
    private String guigeid = null;
    private String guigeimage;
    private String guigetitle;

    @Override
    public void gettext(int str, int position) {
        strs[position] = str;
        if (strs != null) {
            for (int i = 0; i < strs.length; i++) {
                if (strs[i] == 0) {
                    isallcheck = false;
                    break;
                } else {
                    isallcheck = true;
                    continue;
                }
            }
        } else {
            isallcheck = true;
        }
        allguige.setLength(0);
        if (isallcheck) {
            int num = strs.length;
            int[] guigePx = new int[num];
            for (int i = 0; i < num; i++) {
                guigePx[i] = strs[i];
            }

            Arrays.sort(guigePx);
            for (int i = 0; i < mGuigeData.getSpecs().size(); i++) {
                allguige.append(guigePx[i]);
            //    LogUtils.e("allguige1:", allguige.toString());
                if (i != mGuigeData.getSpecs().size() - 1) {
                    allguige.append("_");
                }
            }

            guige = allguige.toString();
            for (int i = 0; i < mGuigeData.getOptions().size(); i++) {

                if (guige.equals(mGuigeData.getOptions().get(i).getSpecs())) {

                    guigejiage = mGuigeData.getOptions().get(i).getMarketprice();
                    guigekuchun = mGuigeData.getOptions().get(i).getStock();

                    guigeid = mGuigeData.getOptions().get(i).getId();
                    guigeimage = mGuigeData.getOptions().get(i).getThumb();
                    guigetitle = mGuigeData.getOptions().get(i).getTitle();
                }
            }
            if (ASUtils.isCanUse(guigejiage)) {
                tvguigeprice.setText(NumberUtils.DecimalFormat(guigejiage));
            }

            if (ASUtils.isCanUse(guigeimage)) {
                Picasso.with(this).load(guigeimage).placeholder(R.mipmap.zhanweitu2).into(ivguigeimage);
            } else {
                ivguigeimage.setImageResource(R.mipmap.zhanweitu2);
            }
            if (Integer.parseInt(guigekuchun) < 0) {
                tvguigekucun.setText("0");
            } else {
                tvguigekucun.setText(guigekuchun);
            }

        }

    }

    @Override
    public void getGroupGuigeError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        if (mThumb_url.size() != 0) {
            ToastUtils.makeToastShort(jsonObject.optString("msg"));
        }
    }


    @Override
    public void onbuySuccess(Object object) {
        Buy_Data data = (Buy_Data) object;
        Intent intent = new Intent(this, OrderAffirmActivity2.class);
        intent.putExtra("goods_data", data);
        intent.putExtra("optionid", guigeid);
        intent.putExtra("goodsid", mGoodId);
        intent.putExtra("total", goodsnum);
        intent.putExtra("price",guigejiage);
        intent.putExtra("tt","1");
        intent.putExtra("flag","3");
        startActivity(intent);

    }

    @Override
    public void onbuyError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
      //  NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
        Intent intent = new Intent(this, AddAddressActivity.class);
        startActivity(intent);

    }
}
